<template>
    <div style="width: 100%;height: 100%;position: relative;">
        <div id="search">
            <el-row>
                <el-form :model="listQuery" :inline="true" ref="formQuery">
                    <el-col :span="8">
                        <el-form-item label="角色" prop="roleName">
                            <el-input size="small" v-model="listQuery.roleName" placeholder="请输入角色" clearable
                            ></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item>
                            <el-button size="small" type="success" icon="el-icon-plus" @click="handleAdd"></el-button>
                            <el-button size="small" type="primary" icon="el-icon-search" @click="search"></el-button>
                            <el-button size="small" @click="resetQuery('formQuery')">重置</el-button>
                        </el-form-item>
                    </el-col>
                </el-form>
            </el-row>
        </div>
        <div id="table">
            <el-table border :data="list" style="width: 100%" v-loading="loading">
                <el-table-column type="index" width="65" label="#序号"></el-table-column>
                <el-table-column prop="roleName" label="角色"></el-table-column>
                <el-table-column prop="roleCode" label="角色编码"></el-table-column>
                <el-table-column prop="remark" label="角色描述"></el-table-column>
                <el-table-column label="操作" width="120px">
                    <template slot-scope="scope" >
                        <el-tooltip class="item" effect="dark" content="编辑" placement="top-start">
                            <el-button size="small" type="text" icon="el-icon-edit"
                                       @click="handleEdit(scope.row)"></el-button>
                        </el-tooltip>
                      <el-tooltip class="item" effect="dark" content="删除" placement="top-start">
                        <el-button size="small" type="text" icon="el-icon-delete"
                                   @click="handleDelete(scope.row)"></el-button>
                      </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
            <!--分页-->
            <div class="block" style="margin-top: 10px;position: absolute;right: 0;">
                <el-pagination :page-sizes="[10,20]" :page-size="listQuery.pageSize"
                               layout="total, sizes, prev, pager, next, jumper" :total="total"
                               @current-change="handleCurrentChange">
                </el-pagination>
            </div>
        </div>
        <!--对话框-->
        <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="40%">
            <el-form :model="form" :rules="rules" ref="form">
                <el-form-item label="角色名" prop="roleName" :label-width="formLabelWidth">
                    <el-input v-model="form.roleName" placeholder="请输入角色名"
                              :disabled="dialogStatus == 'create'?false:true" autocomplete="off"
                              style="width: 56%"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="remark" :label-width="formLabelWidth">
                    <el-input v-model="form.remark" placeholder="请输入角色描述" autocomplete="off"
                              style="width: 56%"></el-input>
                </el-form-item>
                <el-form-item label="角色编码" prop="roleCode" :label-width="formLabelWidth">
                    <el-input v-model="form.roleCode" placeholder="请输入角色编码" autocomplete="off"
                              style="width: 56%" :disabled="dialogStatus == 'create'?false:true"></el-input>
                </el-form-item>

            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitForm">确 定</el-button>
            </div>
        </el-dialog>


        <!--编辑用户权限-->
        <el-dialog :visible.sync="personFormDialog" title="用户权限编辑">
            <el-transfer v-model="userData" :data="userList" :titles="userMenuTitle"
                         @change="changeUserRole"></el-transfer>
            <div style="text-align:right;margin-top: 8px;">
                <el-button @click="closePersonDialog">取消</el-button>
                <el-button v-no-more-click type="primary" @click="confirmUser">确定</el-button>
            </div>
        </el-dialog>

        


    </div>
</template>

<script>
    export default {
        name: "role",
        watch: {
            filterText(val) {
                this.$refs.menuTree.filter(val);
            }
        },
        data() {
            return {
                filterText: '',
                userList: [], //穿梭框待分配权限的用户
                userData: [], //穿梭框已被分配权限的用户
                userMenuTitle: ['用户', '已分配的用户'],
                isShow: true,
                personFormDialog: false,
                menuDialogVisible: false,
                menuData: {
                    roleId: undefined,
                    permissionIds: []
                },
                list: [],
                role: {
                    id: undefined,
                    roleName: undefined,
                    code: undefined,
                    remark: undefined
                },
                total: undefined,
                loading: true,
                dialogStatus: "",
                defaultProps: {
                    children: "children",
                    label: "name"
                },
                dataTree: [], // 菜单权限数据
                currentMenu: [], //被选中的树节点id
                checkKeyKeys: [], //被点击选择的树节点id
                textMap: {
                    create: "新增角色",
                    update: "修改角色"
                },
                //对话框表单标签的宽度
                formLabelWidth: '120px',
                //提交对话框表单里面的数据
                form: {},
                dialogFormVisible: false,
                //查询条件
                listQuery: {
                    //    当前页
                    pageNum: 1,
                    pageSize: 10
                },
                rules: {
                    roleName: [{required: true, message: '请输入角色名', trigger: 'blur'}],
                    remark: [{required: true, message: '请输入角色描述', trigger: 'blur'}],
                    roleCode: [{required: true, message: '请输入角色编码', trigger: 'blur'}]
                }
            }
        },
        methods: {
            //编辑
            handleEdit(row) {
                this.$get('/role/getDetail', {roleId: row.id}).then(res => {
                    if (res.code == 200) {
                        this.form = res.data;
                    }
                });
                this.dialogStatus = "update";
                this.dialogFormVisible = true;

            },
            //关闭用户管理权限框
            closePersonDialog() {
                this.personFormDialog = false;
            },
            changeUserRole(data) {
                console.log("change", data);
                this.userData = data;
            },
            //搜索
            search() {
                // this.loading=true;
                this.getList();

            },
          //删除
          handleDelete(row){
                this.$confirm('此操作删除该用户, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$get('/role/delete', {roleId: row.id}).then(res => {
                    //console.log(res);
                    if (res.code == 200) {
                        this.$message.success("删除成功");
                        this.getList();
                    }else{
                        this.$message.error(res.msg);
                    }
                    });
                }).catch(() => {
                    this.$message({
                    type: 'info',
                    message: '已取消删除'
                    });          
                });
            },
            //分页函数
            handleCurrentChange(val) {
                // console.log(`当前页: ${val}`);
                this.listQuery.pageNum = val;
                this.getList();
            },
            //获取列表
            getList() {
                this.loading = true;
                this.$post("/role/list", this.listQuery).then(res => {
                    if (res.code == 200) {
                        this.loading = false;
                        this.list = res.data.records;
                        this.total = res.data.total;
                    }
                })
            },
            //关闭菜单权限框
            closeMenuDialog(form) {
                this.menuDialogVisible = false;
            },
            //重置
            resetQuery(formName) {
                this.$refs[formName].resetFields();
            },
            //点击新增按钮
            handleAdd() {
                this.dialogStatus = "create";
                //新增之后清空表单
                this.form = {};
                this.dialogFormVisible = true;
            },
            //获取用户
            getUserList(id) {
                this.$get("/role/userList", {roleId: id}).then(res => {
                    if (res.code == 200) {
                        console.log("data", res.data);
                        this.userList = res.data.list;
                        this.userData = res.data.selectIds;
                    }
                });

            },
            //编辑菜单权限
            handleEditMenu(scope) {
                //清空被选择的node节点
                this.currentMenu = [];
                this.menuDialogVisible = true;
                this.menuData.roleId = scope.row.id;
                this.getSelectNode(scope.row.id);
                this.getPermissionTree();
            },
            filterNode(value, data) {
                if (!value) return true;
                return data.name.indexOf(value) !== -1;
            },
            //获取权限菜单树
            getPermissionTree() {
                this.$post("/permission/tree").then(res => {
                    //console.log("res", res.data);
                    if (res.code == 200) {
                        this.dataTree = res.data;
                    }
                });
            },
            //获取当前角色下已被选择的节点
            getSelectNode(id) {
                this.$get("/rolePermission/relation", {id: id}).then(res => {
                    //console.log("checkKeyKeys", res.data.data);
                    if (res.code == 200) {
                        this.currentMenu = res.data;
                    }
                })
            },
            treeNodeChange(node, data) {
                this.checkKeyKeys = data.checkedKeys;
            },
            //打开用户权限分配框
            handleUser(row) {
                this.userData = [];
                this.roleId = row.id;
                this.personFormDialog = true;
                this.getUserList(row.id);
            },

            // 保存提交
            submitForm() {
                this.$refs['form'].validate((valid) => {
                    if (valid) {
                        //    前端数据传给后端
                        this.$post("/role/save", this.form).then(res => {
                            if (res.code == 200) {
                                this.$message.success("操作成功！");
                                //关闭对话框
                                this.dialogFormVisible = false;
                                //    重新渲染刷新数据
                                this.getList();
                            } else {
                                this.$message.error("操作失败！");
                            }
                        })

                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
            },
            handleStatus(status, id) {
                // console.log("asssssss",status);
                // console.log("asssssss",id);
                this.$get("/role/changeStatus", {status: status, roleId: id}).then(res => {
                    if (res.code == 200) {
                        this.$message.success("操作成功！");
                    } else {
                        this.$message.error("操作失败！");
                    }
                });

            },

            //分配用户权限
            async confirmUser() {
                var roleId = this.roleId;
                var data = {
                    roleId: roleId,
                    selectUserIds: this.userData
                };
                this.$post("/role/editUser", data).then(res => {
                    if (res.code == 200) {
                        this.$message.success("修改成功");
                        this.personFormDialog = false;
                    } else {
                        this.$message.error("修改失败");
                    }
                });

            },

            //分配角色菜单权限
            async confirmMenu() {
                this.$refs.roleForm.validate(valid => {
                    let hafCheckedKeys = this.$refs.menuTree.getHalfCheckedKeys();
                    let permissionIds = this.$refs.menuTree.getCheckedKeys();
                    this.menuData.permissionIds = permissionIds;
                    this.menuData.halfStatus = hafCheckedKeys;
                    //this.menuData.permissionIds = this.menuData.permissionIds.concat(hafCheckedKeys);
                    //console.log("res", this.menuData);
                    if (valid) {
                        this.$post("/rolePermission/save", this.menuData).then(res => {
                            if (res.code == 200) {
                                this.$message.success("操作成功");
                                this.menuDialogVisible = false;
                            } else {
                                this.$message.error("操作失败");
                            }
                        });
                    }
                });
            },


        },


        created() {
            // this.init();
            this.getList();
        }
    }
</script>

<style lang="less" scoped>
    #table {
        padding: 0 20px;
    }

    #search {
        padding: 20px;
    }

    .item {
        margin-left: 15px;
    }


</style>
